<?php
namespace Home\Controller\PublicAction;
use Think\Controller;
/*
 * 用户控制器 2016.6.7
 * author:candy
 * 注册、登入
 * 公共操作
 * 忘记密码，没做呢，多次操作添加验证码
 */
class UserController extends Controller {
    
    public function _empty($name){
        $this->display("Event:404");      
    }

    public function index(){
        if(session('?user')){
            if(session('user.type')=='normal')
                redirect(U('Home/User/User/index'));                
            if(session('user.type')=='super')
                redirect(U('Home/Superuser/index'));                
            if(session('user.type')=='storekeeper')
                redirect(U('Home/Superuser/index'));
        }else
            $this->login();
    }

    public function login(){
    	if(!IS_POST){
    		$this->display("Event:login");
    	}else{
    		$User = M('User');
    		$User->create();
    		$result = $User->where('account="'.$User->account.'"')->find();
    		if($result&&md5(I('post.password')) == $User->password){
                $userinfo = $result;
                if ($result['type']=='storekeeper') {
                    $shop = M('shop');
                    $shop_info = $shop->where('user_id',$result['user_id'])->field('shop_id,pic_name,pic_path')->find();
                    //如果是店家添加商铺id到session
                    session('shop',$shop_info);
                }
                session('user',$userinfo);
                if($userinfo['type']=='normal')
                    redirect(U('Home/User/User/index'));                
                if($userinfo['type']=='super')
                    redirect(U('Home/Superuser/index'));                
                if($userinfo['type']=='storekeeper')
                    redirect(U('Home/Superuser/index'));
    		}else{
    			$this->error('登入失败');
    		}
    	}
    }

    public function register(){
    	if(!IS_POST){
    		$this->display("Event:register");
    	}else{
    		$User = M('User');
    		$User->create();
            date_default_timezone_set('PRC');   
            $createTime =  date('Y-m-d H:i:s');
            $User->datetime = $createTime;
            $User->name = $User->account;
            $User->type = 'normal';
    		if($User->add()){
    			$this->success('注册成功', U('Home/Publicaction/User/login'));
    		}else{
    			$this->error('注册失败');
    		}
    	}
    }

    /**
     * 6.6
     * 判断账号是否被注册过
     */
    public function checkIsRegister($account=NULL){
        $User = M('User');
        $result = $User->where('account="'.$account.'"')->find();
        if($result)echo 1;
        else echo 0;
    }


    /**
     * 7.13
     * 修改用户等级
     */
    public function level($id=null,$level=null){
        if($id&&$level){
            $user = M('User');
            $user->level = $level;
            if($user->where(array('user_id'=>$id))->save()){
                $this->success();
            }else{
                $this->error();
            }
            
        }
    }

}